package com.ruoyi.server.utils;

import com.ruoyi.server.enums.AddConstants5;
import com.ruoyi.server.enums.CmdConstants;
import com.ruoyi.server.pkg.SendMsg;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 *  申请工具
 *
 * @author OpenACloud
 * @create 2024/6/13 8:23
 */
public class ApplicationUtil {


    /**
     * 申请用户
     */
    public static boolean applicationFriend(ChannelHandlerContext ctx, SendMsg sendMsg){
        Set<Long> userFriend2 = ctx.attr(OnlineUtil.USER_FRIEND).get();
        if(userFriend2.contains(sendMsg.RECEIVEID)) {
            SendMsg errorMsg = new SendMsg();
            errorMsg.CMD = AddConstants5.ADD_APPLICATION;
            errorMsg.STATUS = AddConstants5.ADD_FAIL;
            errorMsg.SENDID = sendMsg.SENDID;
            errorMsg.CONTEXT = "好友已存在";
            ctx.channel().writeAndFlush(errorMsg);
            return false;
        }


        ChannelHandlerContext userCtx = OnlineUtil.ONLINE_MAPS.get(sendMsg.RECEIVEID);
        if(Objects.nonNull(userCtx) && sendMsg.STATUS == AddConstants5.ADD_SUCCESS) {
            userFriend2.add(sendMsg.RECEIVEID);
            ctx.attr(OnlineUtil.USER_FRIEND).set(userFriend2);

            Set<Long> userFriend1 = userCtx.attr(OnlineUtil.USER_FRIEND).get();
            userFriend1.add(sendMsg.SENDID);
            userCtx.attr(OnlineUtil.USER_FRIEND).set(userFriend1);
            userCtx.channel().writeAndFlush(sendMsg);
        }
        return sendMsg.STATUS == AddConstants5.ADD_SUCCESS;
    }


    /**
     * 申请群聊
     */
    public static boolean applicationGroup(ChannelHandlerContext ctx, SendMsg sendMsg){
        Byte APPLICATION_STATUS_GROUP = sendMsg.STATUS;
        if (APPLICATION_STATUS_GROUP == AddConstants5.ADD_SUCCESS) {
            //TODO 刷新下列表
            return true;
        }
        ctx.channel().writeAndFlush(sendMsg);
        HashMap<Long, Set<Long>> apGroup = ctx.attr(AddUtil.ADD_APPLICATION_GROUP).get();
        apGroup.remove(sendMsg.GROUPID);
        ctx.attr(AddUtil.ADD_APPLICATION_GROUP).set(apGroup);
        return false;
    }

}
